package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {


    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    

    @Override
    public List<CourseCategoryTreeDto> selectTreeNodes(String id) {
        //调用mapper层查询 （数据库递归）
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);

        //找到每个节点的子节点，最终封装成List<CourseCategoryTreeDto>

        //转化成一个map，map的key是节点id，value是节点对象
        Map<String, CourseCategoryTreeDto> map = courseCategoryTreeDtos.stream()
                .filter(item -> !id.equals(item.getId()))
                .collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));

        //最终返回的list
        List<CourseCategoryTreeDto> categoryTreeDtos = new ArrayList<>();


        courseCategoryTreeDtos.stream()
                .filter(item -> !id.equals(item.getId()))
                .forEach(item -> {
                    if (item.getParentid().equals(id)){
                        categoryTreeDtos.add(item);
                    }

                    CourseCategoryTreeDto courseCategoryTreeDto = map.get(item.getParentid());
                    if (courseCategoryTreeDto!=null){
                        if (courseCategoryTreeDto.getChildrenTreeNodes()==null){
                            courseCategoryTreeDto.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                            courseCategoryTreeDto.getChildrenTreeNodes().add(item);
                        }else {
                            courseCategoryTreeDto.getChildrenTreeNodes().add(item);
                        }
                    }
                });

        return categoryTreeDtos;
    }
    
    
}
